/*
 *	create by senllang 2023/5/3
 *  mail : study@senllang.onaliyun.com
 *	
 */


#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "ipc_shmem.h"

/* 全局变量，记录共享内存的信息 */
stShMem shmemInfo;

/*
 * 创建指定size大小的共享内存
 *
 * create by senllang 2023/5/2
 *
 * pShmem：传出共享内存的地址
 * size  : 指定共享内存的大小
 */
int CreateShMem(char **pShmem, int size)
{
	if(size <= 0)
	{
		printf("share memory size invalid.\n");
		return -1;
	}
	
	shmemInfo.ShMemKey = IPC_PRIVATE;
	shmemInfo.ShMemId = shmget(shmemInfo.ShMemKey, size, 0600|IPC_CREAT);
	if(shmemInfo.ShMemId < 0)
    {
        printf("get shm error [%s]\n",strerror(errno));
        return -1;
    }
	
	shmemInfo.ShMemSize = size;
	shmemInfo.pShMemStartAddr = (char *)shmat(shmemInfo.ShMemId, NULL, 0);
	if(shmemInfo.pShMemStartAddr == (char *)-1)
    {
        printf("attach sharememory error [%s]\n", strerror(errno));
        return -1;
    }

	*pShmem = shmemInfo.pShMemStartAddr;
	return 0;
}

/*
 * 解除共享内存的映射，并销毁
 *
 * create by senllang 2023/5/2
 *
 * IsDestroy：是否需要销毁，!=0 时，解除并销毁；=0,只解除映射
 */
int DestroyShMem(int IsDestroy)
{
	if(-1 == shmdt(shmemInfo.pShMemStartAddr))
    {
        printf("detach sharememory error [%s]\n",strerror(errno));
        return -1;
    }
	
	if(IsDestroy)
		shmctl(shmemInfo.ShMemId, IPC_RMID, NULL);
	
	return 0;
}
